
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
import { fileURLToPath } from 'url'
import path from 'path'
import { start } from 'repl'
const __filenameNew = fileURLToPath(import.meta.url)
const __dirnameNew = path.dirname(__filenameNew)

var express = require('express')

const app = express()

app.use(express.static(__dirnameNew + '/dist'))

const bodyparser = require('body-parser') // 获取post模块
const request = require('request')
const bsaeIp = 'http://119.23.250.210:9527/'

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin)
  // res.header("Access-Control-Allow-Origin", '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('Access-Control-Allow-Credentials', 'true')
  res.header('X-Powered-By', ' 3.2.1')
  if (req.method === 'OPTIONS') res.send(200)/* 让options请求快速返回*/
  else next()
})
app.use(bodyparser.urlencoded({ txtended: false }))
// parse application/json
app.use(bodyparser.json())

// var imgUrl = 'http://49.232.143.202:1662/thing/rsm/3161962125001218/configure/other/'

// var img1 = imgUrl + '16a018eb5c8c311c1ec2310b017447b7/晴天.png'
// var img2 = imgUrl + '68adbb52bf020ad5c0c8ecabcb7d46cc/阴天.png'
// var img3 = imgUrl + '2ab1e9dda9494c44244dfd90a3466f26/多云.png'
// var img4 = imgUrl + '379fef57d18c25fddf4c09479eb47332/暴雪.png'
// var img5 = imgUrl + '379fef57d18c25f/configure/other/d990399cf607d20c74f19161958db672/小雨.png'

var img1 = 'https://thingjsx.thingjs.com/thing/rsm/3953275746789151/configure/other/16a018eb5c8c311c1ec2310b017447b7/%E6%99%B4%E5%A4%A9.png'
// 多云
var img3 = 'https://thingjsx.thingjs.com/thing/rsm/3953275746789151/configure/other/2ab1e9dda9494c44244dfd90a3466f26/%E5%A4%9A%E4%BA%91.png'
var img2 = 'https://thingjsx.thingjs.com/thing/rsm/3953275746789151/configure/other/2ab1e9dda9494c44244dfd90a3466f26/%E5%A4%9A%E4%BA%91.png'
// 雪

var img4 = 'https://thingjsx.thingjs.com/thing/rsm/3953275746789151/configure/other/379fef57d18c25fddf4c09479eb47332/%E6%9A%B4%E9%9B%AA.png'
// 小雨
var img5 = 'https://img.v4.thingjs.com/thing/rsm/3953275746789151/configure/other/d990399cf607d20c74f19161958db672/%E5%B0%8F%E9%9B%A8.png'

const headers = {
  'energyToken': '',
  'checkToken': '',
  'cookie': ''
  // 'content-type': 'application/json'
}
let now = ''
// 获取年份
var year = ''
// 获取月份
var month = ''

// 获取日期
var day = ''
// 当前月份和上个月的时间
var currentDate = ''
var aftercurrentDate = ''
const getTime = () => {
  // 使用Date对象获取当前时间
  now = new Date()
  // 获取年份
  year = now.getFullYear()
  // 获取月份
  month = now.getMonth() + 1
  // 月份小于10，在前面补0
  if (month < 10) {
    month = '0' + month
  }
  // 获取日期
  day = now.getDate()
  // 日期小于10，在前面补0
  // if (this.day < 10) {
  //   this.day = '0' + this.day;
  // }
  currentDate = year + '-' + month + '-' + (day < 10 ? ('0' + day) : day)

  if (month == '01') {
    aftercurrentDate = (year - 1) + '-' + '12' + '-' + (day < 10 ? ('0' + day) : day)
  } else if (now.getMonth() < 10) {
    aftercurrentDate = year + '-' + '0' + now.getMonth() + '-' + (day < 10 ? ('0' + day) : day)
  } else {
    aftercurrentDate = year + '-' + now.getMonth() + '-' + (day < 10 ? ('0' + day) : day)
  }
}
getTime()
let timer = 0
const login = () => {
  request(bsaeIp + 'api/user/login?username=510000A007015&password=95f06c95a8f3ccb8b5886a8d962487b8aed251fcb6e38db42f11bd56999c3c3e', { json: true }, (err, res2, body) => {
    if (err) {
      return console.log(err)
    }
    // console.log('body=======>', body);
    res2.rawHeaders.forEach(el => {
      if (el.indexOf('energyToken') != -1) {
        headers.energyToken = el.split(';')[0].split('=')[1]
        headers.cookie = el.split(';')[0]
      }

      if (el.indexOf('checkToken') != -1) {
        headers.checkToken = el.split(';')[0].split('=')[1]
        headers.cookie += ';' + el.split(';')[0]
      }
    })
  })
}
login()
setInterval(() => {
  timer += 10
  if (timer == 110) {
    timer = 0
    login()
  }
}, 600000)

app.get('/web', (req, res) => {
  // 关闭已经开启的websocket
  res.sendFile(__dirnameNew + '/dist/' + 'index.html')
  // res(express.static(path.join(__dirnameNew, 'dist')))
})

app.get('/login',
  (req, res) => {
    login()
    res.send('1')
  }
)

// 获取 近30天数据
app.get('/rankingEnergy',
  (req, res) => {
    // let bodyData = { ...req.body }
    request({
      url: bsaeIp + `/api/query/bigScreen/rankingEnergy/${req.query.energyType}/30`,
      method: 'GET',
      headers: headers,
      json: true
    }, (err, res2, body) => {
      // console.log('dddddddddd', req.query.energyType, body)
      if (err) {
        return console.log(err)
      }
      var data = []
      body.data.names.splice(0, 20).forEach((el, idx) => {
        if (el != '总水表') {
          data.push({ instrumentName: el, totalEnergy: body.data.values[idx] })
        }
      })
      data.forEach((el, idx) => {
        el.idx = idx + 1
      })
      // , idx: idx + 1
      // data2.forEach((el,idx)=>{
      // })
      res.send(data)
    })
  }
)
// 获取24小时趋势
app.get('/realTimeEnergy4Electric',
  (req, res) => {
    // let bodyData = { ...req.body }
    // realTimeEnergy4Electric 电
    // thisYearTotalEnergy4Water 水
    request({
      // /api/query/bigScreen/thisYearTotalEnergy4Water/24
      url: bsaeIp + `/api/query/bigScreen/${req.query.energyType == 1 ? 'realTimeEnergy4Electric' : 'thisYearTotalEnergy4Water'}/${req.query.time}`,
      method: 'GET',
      headers: headers,
      json: true
    }, (err, res2, body) => {
      // console.log(err, res2, body)
      if (err) {
        return console.log(err)
      }

      var data = body.data

      data.names.forEach((el, idx) => {
        data.names[idx] = el.substring(11, 13) + '点'
      })
      console.log(data)
      res.send(data)
    })
  }
)

// 获取基础信息
app.get('/getBaseInfo',
  (req, res) => {
    request({
      url: `${bsaeIp}api/query/bigScreen/getBaseInfo/${req.query.energyType}`,
      method: 'GET',
      headers: headers,
      json: true
    }, (err, res2, body) => {
      if (err) {
        return console.log(err)
      }
      res.send(body)
    })
  }
)
// 获取每日水电统计
app.get('/dayEnergy4',
  (req, res) => {
    request({
      url: `${bsaeIp}api/query/bigScreen/dayEnergy4Electric/${req.query.day}`,
      method: 'GET',
      headers: headers,
      json: true
    }, (err, res2, body) => {
      if (err) {
        return console.log(err)
      }
      request({
        url: `${bsaeIp}api/query/bigScreen/dayEnergy4Water/${req.query.day}`,
        method: 'GET',
        headers: headers,
        json: true
      }, (err0, res3, body2) => {
        if (err0) {
          res.send(body)
          return console.log(err0)
        }
        body2.data.electric = body.data.values
        res.send(body2)
      })
    })
  }
)
// 获取四川天气
app.get('/weather',
  (req, res) => {
    request({
      url: 'https://weather.cma.cn/api/weather/view?stationid=56286',
      method: 'GET',
      headers: headers,
      json: true
    }, (err, res2, body) => {
      if (err) {
        return console.log(err)
      }
      // data.

      var imgNow1 = ''
      var daily = body.data.daily[0]
      var nowT = body.data.now
      // console.log('body====>',nowT)
      if (daily.dayText == '晴') {
        imgNow1 = img1
      } else if (daily.dayText == '阴') {
        imgNow1 = img2
      } else if (daily.dayText == '多云') {
        imgNow1 = img3
      } else if (daily.dayText.indexOf('雨') != -1) {
        imgNow1 = img5
      } else if (daily.dayText.indexOf('雪') != -1) {
        imgNow1 = img4
      }
      var resData = {
        imgUrl: imgNow1,
        tianqi: daily.dayText == daily.nightText ? daily.dayText : daily.dayText + '转' + daily.nightText,
        nowtemperature: nowT.temperature,
        windDirection: nowT.windDirection + ' ' + nowT.windScale,
        humidity: nowT.humidity
      }
      res.send(resData)
    })
  }
)

// 获取最新告警信息
app.get('/pagingQuery',
  (req, res) => {
    getTime()
    request({
      url: `${bsaeIp}api/warnRealLog/pagingQuery`,
      method: 'POST',
      headers: headers,
      body: {
        'current': 1,
        'size': 1,
        'startTime': aftercurrentDate + ' 12:00:00',
        'endTime': currentDate + ' 12:00:00'
      },
      json: true
    }, (err, res2, body) => {
      // var current = Math.floor(body.data.total / 10) + 1

      // if (err) {
      //     return console.log(err);
      // }
      if (body.data.records.length > 0) {
        res.send(body2.data.records[body2.data.records.length - 1])
      } else {
        res.send('')
      }
    })
  }
)
// https://weather.cma.cn/api/weather/view?stationid=57083
app.listen(1111, function() {
  console.log('启动')
})

